<template>
  <div class="role_wrap">
    <div v-loading="loading" class="role_container">
      <!-- 角色顶栏 -->
      <div class="role_top">
        <div class="top_left">
          <el-input
            v-model="searchForm.userName"
            size="small"
            style="width: 200px; margin-right: 10px"
            prefix-icon="el-icon-search"
            placeholder="请输入用户名称"
          />
        </div>
        <div class="top_right">
          <el-button
            class="top_right_button"
            icon="el-icon-search"
            type="primary"
            size="mini"
            @click="getUserList"
          >查询</el-button>
          <el-button
            v-if="buttonPerminssion.includes('users_save')"
            class="top_right_button"
            icon="el-icon-circle-plus-outline"
            type="primary"
            size="mini"
            @click="
              addRoleVisible = true
              addRoleType = 'add'
            "
          >新增</el-button>
          <el-button
            v-if="buttonPerminssion.includes('users_delete')"
            class="top_right_button"
            icon="el-icon-delete"
            style="width: 86px; padding: 0"
            type="danger"
            size="mini"
            @click="MultipleSelectionRemove(false)"
          >勾选删除</el-button>
        </div>
      </div>
      <!-- 角色表格 -->
      <div class="role_table">
        <el-table
          ref="multipleTable"
          :header-cell-style="{ background: '#f3f6ff' }"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <!-- 自定义暂无数据 -->
          <template slot="empty">
            <el-empty :image-size="100" description="暂无数据" />
          </template>
          <el-table-column align="center" type="selection" width="55" />
          <el-table-column
            v-if="
              isShowOperationCol([
                'users_update',
                'users_delete',
                'users_resetpwd',
                'users_allot',
              ])
            "
            label="操作"
            width="260"
          >
            <template slot-scope="scope">
              <div style="color: #4d6aff">
                <el-button
                  v-if="buttonPerminssion.includes('users_update')"
                  type="primary"
                  style="
                    padding: 3px 10px;
                    border-radius: 2px;
                    margin-right: 5px;
                  "
                  @click="userInfoEdit(scope.row, true)"
                >编辑</el-button>
                <el-popconfirm
                  :title="`确定将名称为【${scope.row.userName}】的用户删除吗？`"
                  @confirm="userInfoRemove([scope.row.id])"
                >
                  <el-button
                    v-if="buttonPerminssion.includes('users_delete')"
                    slot="reference"
                    type="danger"
                    style="
                      padding: 3px 10px;
                      border-radius: 2px;
                      margin-right: 5px;
                    "
                  >删除</el-button>
                </el-popconfirm>
                <el-button
                  v-if="buttonPerminssion.includes('users_resetpwd')"
                  type="warning"
                  style="
                    padding: 3px 10px;
                    border-radius: 2px;
                    margin-right: 5px;
                  "
                  @click="userInfoEdit(scope.row, false)"
                >密码</el-button>
                <el-button
                  v-if="buttonPerminssion.includes('users_allot')"
                  type="success"
                  style="
                    padding: 3px 10px;
                    border-radius: 2px;
                    margin: 0;
                    margin-right: 5px;
                  "
                  @click="permissionClick(scope.row)"
                >终端</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="userName" align="center" label="用户名称" />
          <el-table-column prop="account" align="center" label="账号" />
          <el-table-column prop="roleName" align="center" label="角色" />
          <el-table-column prop="googleStatus" align="center" label="账号状态">
            <template slot-scope="scope">
              <span
                v-if="scope.row.googleStatus === 0"
                style="color: #cd6864"
              >未绑定</span>
              <span
                v-if="scope.row.googleStatus === 1"
                style="color: #66b787"
              >已绑定</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" align="center" label="创建时间" />
          <el-table-column prop="remark" align="center" label="备注" />
        </el-table>
        <el-pagination
          style="margin-top: 15px; margin-right: 10px; text-align: end"
          :current-page="tablePage.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="tablePage.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tablePage.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 新增、编辑角色抽屉 -->
    <el-drawer
      :size="500"
      :title="addRoleType === 'add' ? '新增用户' : '编辑用户'"
      :visible.sync="addRoleVisible"
      :before-close="drawerHandleClose"
    >
      <addRoleDrawer
        v-if="addRoleVisible"
        :type="addRoleType"
        :curr-role="currUser"
        @drawerBtnClose="drawerBtnClose"
      />
    </el-drawer>
    <!-- 勾选删除弹层 -->
    <el-dialog title="消息" :visible.sync="removeVisible" width="400px" center>
      <div style="font-size: 16px">
        <i
          class="el-icon-warning-outline"
          style="color: #ff9900; margin-right: 10px"
        />
        <span>{{ removeMsg }}</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="removeVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="MultipleSelectionRemove(true)"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 重置密码 -->
    <el-dialog title="重置密码" :visible.sync="resetPwd" width="400px" center>
      <div style="font-size: 16px; display: flex; justify-content: center">
        <el-input
          v-model="passWord"
          placeholder="请输入密码"
          style="width: 300px"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="resetPwd = false">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="passwdReset"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <assignPermissions
      v-if="permissionVisible"
      :all-tree-terminal="allTreeTerminal"
      :permission-visible.sync="permissionVisible"
      :curr-user="currUser"
    />
  </div>
</template>

<script>
import { buttonPermission } from '@/mixins/mixin.js'
import assignPermissions from './components/assignPermissions'
import addRoleDrawer from './components/addRoleDrawer'
import {
  getUserList,
  userInfoRemove,
  passwdReset
} from '@/api/userManage/users'
import { getAllTreeTerminal } from '@/api/directory'
export default {
  name: 'Users',
  components: {
    addRoleDrawer,
    assignPermissions
  },
  mixins: [buttonPermission],
  data() {
    return {
      loading: true,
      permissionVisible: false,
      passWord: '',
      resetPwd: false, // 控制重置密码弹层
      searchForm: {
        userName: ''
      },
      tableData: [], // 表格数据
      multipleSelection: [], // 当前勾选数据
      currUser: {}, // 当前选中角色
      tablePage: {
        page: 1,
        limit: 10,
        total: 0
      },
      addRoleVisible: false, // 控制添加角色弹层
      addRoleType: 'add', // 角色弹层类型
      removeMsg: '', // 删除消息提示内容
      removeVisible: false, // 删除消息弹层控制
      allTreeTerminal: []
    }
  },
  watch: {
    searchForm: {
      handler(newVal, oldVal) {
        // todo
        this.tablePage.page = 1
      },
      immediate: true,
      deep: true // 可以深度检测到 person 对象的属性值的变化
    }
  },
  async created() {
    await Promise.all([this.getAllTreeTerminal(), this.getUserList()])
    this.loading = false
  },
  methods: {
    async getAllTreeTerminal() {
      if (!this.buttonPerminssion.includes('getAllTreeTerminal')) return
      try {
        const res = await getAllTreeTerminal()
        if (res.success) {
          this.allTreeTerminal = res.result
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 获取用户列表数据
    async getUserList() {
      // const formData = new FormData()
      // formData.append('name', this.userName)
      // formData.append('page', this.tablePage.page)
      // formData.append('limit', this.tablePage.limit)
      const params = {
        page: this.tablePage.page,
        limit: this.tablePage.limit,
        userName: this.searchForm.userName
      }
      try {
        const res = await getUserList(params)
        if (res.success) {
          this.tableData = res.result.list
          this.tablePage.total = res.result.total
        }
      } catch (error) {
        console.log(error)
      }
    },
    permissionClick(row) {
      this.currUser = row
      this.permissionVisible = true
    },
    // 重置密码接口
    async passwdReset() {
      try {
        const params = {
          id: this.currUser.id,
          passWord: this.passWord
        }
        const res = await passwdReset(params)
        if (res.success) {
          this.$message.success(
            `【${this.currUser.userName}】用户的密码修改成功`
          )
          this.resetPwd = false
        } else {
          return false
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑角色按钮点击事件
    userInfoEdit(row, isEdit) {
      if (isEdit) {
        this.addRoleVisible = true
      } else {
        this.resetPwd = true
      }
      this.addRoleType = 'edit'
      this.currUser = row
    },
    // 角色删除
    async userInfoRemove(ids) {
      const params = {
        idList: ids
      }
      try {
        const res = await userInfoRemove(params)
        if (res.success) {
          await this.getUserList()
          this.$message.success('删除成功')
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 勾选删除按钮点击事件句柄
    async MultipleSelectionRemove(isSure) {
      if (isSure) {
        const ids = this.multipleSelection.map((item) => item.id)
        await this.userInfoRemove(ids)
        this.removeVisible = false
      } else {
        if (this.multipleSelection.length === 0) {
          return this.$message('请勾选需要删除的用户')
        }
        this.removeMsg = '确定删除勾选的用户吗？'
        this.removeVisible = true
      }
    },
    // 添加、编辑抽屉弹层关闭之前回调函数
    drawerHandleClose() {
      this.currUser = {}
      this.addRoleVisible = false
    },
    /**
     * @description: 监听抽屉内确认、取消提交按钮
     * @param {Boolean} bool true-确认按钮 false-取消按钮
     * @return {*}
     * @Date: 2023-04-20 11:07:23
     */
    drawerBtnClose(bool) {
      if (bool) {
        this.getUserList()
      }
      this.addRoleVisible = false
    },
    // 监听表格多选数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.tablePage.limit = val
      this.tablePage.page = 1
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.tablePage.page = val
      this.getUserList()
    }
  }
}
</script>

<style lang="scss" scoped>
.role_wrap {
  padding: 10px;
  height: 100%;
  overflow-y: auto;
  .role_container {
    border-radius: 6px;
    min-height: 100%;
    background-color: #fff;
    .role_top {
      padding: 15px;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .top_left {
        flex: 2;
        display: flex;
        flex-wrap: wrap;
      }
      .top_right {
        flex: 1;
        display: flex;
        justify-content: flex-end;
        .top_right_button {
          height: 30px;
          margin: 0 7px 0 0;
        }
      }
    }
  }
}
</style>
